package com.yj.web.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * Employee: yesiming
 * Date: 13-11-6
 * Time: 下午6:05
 * To change this template use File | Settings | File Templates.
 */
public class ConfigUtils {

    private static final Log logger = LogFactory.getLog(ConfigUtils.class);

    private static final Map<String, String> errorCodeMsgMap = new HashMap<String, String>();

    private static final String ERROR_CODE_MSG_PROP_FILE = "errorcode-en.properties";

    static {
        loadProp();
    }

    public static void loadProp() {

        InputStream inputStream = ConfigUtils.class.getClassLoader().getResourceAsStream(ERROR_CODE_MSG_PROP_FILE);
        Properties p = new Properties();
        if (inputStream == null) {
            logger.error(ERROR_CODE_MSG_PROP_FILE + " open failed!");
            return;
        }
        try {
            p.load(inputStream);

            if (p == null || p.size() == 0) {
                logger.error("Invalid " + ERROR_CODE_MSG_PROP_FILE + "!");
                return;
            }

            for (Map.Entry entry : p.entrySet()) {
                if (entry != null) {
                    errorCodeMsgMap.put((String) entry.getKey(), StringUtils.defaultString((String) entry.getValue(), ""));
                }
            }
            if (errorCodeMsgMap != null) {
                logger.info(ERROR_CODE_MSG_PROP_FILE + " loaded. size:" + errorCodeMsgMap.size() + ".");
            }
        } catch (Exception e) {
            logger.error("loadProp", e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error("loadProp", e);
            }
        }
    }

    public static String getMsgByErrorCode(int code) {
        String msg = errorCodeMsgMap.get(String.valueOf(code));
        return msg == null ? "" : msg;
    }

    public static String getGoogleCallBackDomain() {
        String mode = System.getProperty("GG_API_MODE");
        logger.info("GG_API_MODE=" + mode);
        if (!StringUtils.isEmpty(mode) && "dev".equals(mode)) {
            return "gmailcallback.quadapp.com";
        } else {
            return "www.quadapp.com";
        }
    }


}
